{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "1、导入第三方包"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "import requests\n",
    "# 请求\n",
    "from bs4 import BeautifulSoup\n",
    "# 解析"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "2、获取西游记"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [],
   "source": [
    "url='https://xiyouji.5000yan.com/'\n",
    "# 西游记目录\n",
    "file=open('data/xiyouji_01.txt','w')\n",
    "# 文本写入对象\n",
    "response=requests.get(url)\n",
    "# 请求目录页\n",
    "soup=BeautifulSoup(response.content)\n",
    "# 解析目录页\n",
    "xiyouji_chapters=soup.find('div',class_='p-2 my-2 bg-white rounded').ul.children\n",
    "# 获取章回内容\n",
    "for cpt in xiyouji_chapters:\n",
    "    # 迭代访问章节内容\n",
    "    if cpt !='\\n' and cpt is not None:\n",
    "        link=cpt.a.get('href')\n",
    "        # 获取章节地址\n",
    "        cpt_page=requests.get(link)\n",
    "        # 请求章节页面\n",
    "        cpt_content=BeautifulSoup(cpt_page.content).find('div',class_='py-2 px-2 px-md-4 bg-white divider')\n",
    "        # 获取章节内容\n",
    "        file.write('\\n'+cpt_content.text+'\\n')\n",
    "        # 写入本地文本\n",
    "file.flush()\n",
    "# 把缓存中的数据写入文本\n",
    "file.close()\n",
    "# 关闭文本流"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "base",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.12.4"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
